package cn.lx.es.query.processor;

import cn.lx.es.query.annotation.SearchProcessor;
import cn.lx.es.query.annotation.TermsSearch;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;

/**
 * 内置处理器 - 多值匹配处理器
 */
@SearchProcessor
public class SearchTermsProcessor implements SearchAnnotationProcessor<TermsSearch> {
    @Override
    public void process(TermsSearch annotation, Field field, Object value, BoolQueryBuilder boolQueryBuilder) {
        Collection<?> values = null;
        if (value instanceof String) {
            String str = (String) value;
            if (!str.trim().isEmpty()) {
                values = Arrays.stream(str.split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .collect(Collectors.toList());
            }
        } else if (value instanceof Collection) {
            values = (Collection<?>) value;
        }
        if (values != null && !values.isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.termsQuery(field.getName(), values));
        }
    }
    @Override
    public Class<TermsSearch> getAnnotationType() {
        return TermsSearch.class;
    }
}
